<route lang="yaml">
meta:
  enabled: false
        </route>

<script lang="ts" setup>
import { VXETable } from 'vxe-table'
import type { VxeColumnPropTypes, VxeFormEvents, VxeFormInstance, VxePagerEvents, VxeTableInstance } from 'vxe-table'
import { ElMessage } from 'element-plus'
import apiOrder from '@/api/modules/order'
import apiOrderDetail from '@/api/modules/order_detail'
import apiMerchants from '@/api/modules/merchants'
import apiRoute from '@/api/modules/route'

const g = useGlobalProperties()
const refModalForm = ref<VxeFormInstance>()
const pageData = reactive({
  loading: false,
  tableData: [] as any[],
  // 弹窗相关
  modalShow: false,
  modalName: '',
  priorityLevelList: [] as any[],
  storageTypeList: [] as any[],
  routeList: [] as any[],
  orderDeliveryStateList: [] as any[],
  tablePrint: {
    // 自定义打印的样式示例
    style: `
                .vxe-table {
                  color: #000000; // 修改表格默认颜色
                  font-size: 12px; // 修改表格默认字体大小
                  font-family: "Microsoft YaHei",微软雅黑,"MicrosoftJhengHei",华文细黑,STHeiti,MingLiu; // 修改表格默认字体
                }
                .vxe-table,
                .vxe-table thead th,
                .vxe-table tbody td,
                .vxe-table tfoot td  {
                  border-color: #000000; // 修改表格边框颜色
                }
                .vxe-table thead th {
                  color: green; // 修改表头字体颜色
                  font-size: 14px; // 修改表头默认字体大小
                }
                .vxe-table tfoot td {
                  color: red; // 修改表尾字体颜色
                }
                `,
  },
})
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})
interface ModalForm {
  id: number
  name: string
  principal: string
  addr: string
  phone: string
}
const modalFormData = ref<ModalForm>({
  id: 0,
  name: '',
  principal: '',
  addr: '',
  phone: '',
})
const formRules = {
  name: [
    { required: true, message: '请输入名称' },
  ],
}
interface FormDataVO {
  orderCode: string
  billSn: string
  customerName: string
  routeName: string
  priorityLevel: string
  status: string
  tempType: string
}
const formTop = reactive<FormDataVO>({
  orderCode: '',
  billSn: '',
  customerName: '',
  routeName: '',
  priorityLevel: '',
  status: '',
  tempType: '',
})
function sumbitModalEvent() {
  refModalForm.value?.validate((valid) => {
    if (!valid) { // 校验通过
      apiOrder.createOrUpdate(modalFormData.value).then((res: any) => {
        pageData.modalShow = false
        // tablePage.currentPage = 1
        // tablePage.pageSize = 10
        const req = {
          pageIndex: tablePage.currentPage,
          pageSize: tablePage.pageSize,
          billSn: formTop.billSn,
          priorityLevel: formTop.priorityLevel,
          orderCode: formTop.orderCode,
          customerName: formTop.customerName,
          routeName: formTop.routeName,
          status: formTop.status,
          tempType: formTop.tempType,
        }
        apiPage(req)
      }).catch((e: any) => {
        if (e.msg) {
          ElMessage.error({
            message: e.msg,
            center: true,
          })
        }
      })
    }
  })
}
function cancelModalEvent() {
  pageData.modalShow = false
}
const tableRef = ref<VxeTableInstance>()
/// /////////////////////////////////////时间格式化
// const formatterTime: VxeColumnPropTypes.Formatter<any> = ({ cellValue }) => {
//   return dayjs(cellValue).format('YYYY-MM-DD')
// }
const formatterPriorityLevel: VxeColumnPropTypes.Formatter<any> = ({ cellValue }) => {
  const res = g.selectDictLabel(pageData.priorityLevelList, cellValue)
  return res
}
const formatterStorageType: VxeColumnPropTypes.Formatter<any> = ({ cellValue }) => {
  const res = g.selectDictLabel(pageData.storageTypeList, cellValue)
  return res
}
const formatterDeliveryStatus: VxeColumnPropTypes.Formatter<any> = ({ cellValue }) => {
  const res = g.selectDictLabel(pageData.orderDeliveryStateList, cellValue)
  return res
}
function funcStorageType(cellValue: any) {
  const res = g.selectDictLabel(pageData.storageTypeList, cellValue)
  return res
}
/// ///////////////////////////////////右侧按钮相关
function delItem(row: any) {
  VXETable.modal.confirm('确定删除？').then((res) => {
    if (res === 'confirm') {
      apiOrder.del(row.id).then((res: any) => {
        const $table = tableRef.value
        $table?.remove(row)
      })
    }
  })
}
function editItem(row: any) {
  pageData.modalName = '编辑'
  modalFormData.value = row
  pageData.modalShow = true
}
function sumbitTemp(row: any) {
  VXETable.modal.confirm('确定提交').then((res) => {
    if (res === 'confirm') {
      // console.log(row)
      apiOrder.createOrUpdate(row).then((res) => {
        ElMessage.success({
          message: '提交成功',
          center: true,
        })
      }).catch((e) => {
        if (e && e.msg) {
          ElMessage.error({
            message: e.msg,
            center: true,
          })
        }
      })
    }
  })
}
/// ///////////////////////////////////top按钮相关
function newOrg() {
  pageData.modalName = '新增'
  modalFormData.value = {} as any
  pageData.modalShow = true
}
function removeSelected() {
  const $table = tableRef.value
  if ($table?.getCheckboxRecords().length === 0) {
    ElMessage.error({
      message: '请选中删除行',
      center: true,
    })
    return
  }
  VXETable.modal.confirm('确定删除！！！').then((res) => {
    if (res === 'confirm') {
      const ids = $table?.getCheckboxRecords().map(item => item.id)
      apiOrder.delBatch(ids).then((res: any) => {
        $table?.removeCheckboxRow()
      })
    }
  })
}
function manualSync() {
  apiOrder.syncInfo({}).then((res) => {
    ElMessage.success({
      message: '开始同步',
      center: true,
    })
  }).catch((e) => {
    if (e && e.msg) {
      ElMessage.error({
        message: e.msg,
        center: true,
      })
    }
  })
}
/// ///////////////////////////////////api
function apiPage(req: any) {
  pageData.loading = true
  apiOrder.page(req).then((res) => {
    pageData.tableData = res.data.list
    tablePage.total = res.data.total
    pageData.loading = false
  }).catch((err) => {
    ElMessage.error({
      message: JSON.stringify(err),
      center: true,
    })
    pageData.loading = false
  })
}
function apiListRoute() {
  apiRoute.list({}).then((res: any) => {
    pageData.routeList = res.data.list
  })
}
/// ////////////////////////////table expand
function loadContentMethod({ row }: { row: any }) {
  return new Promise<void>((resolve) => {
    apiOrderDetail.list({ orderCode: row.order_code }).then((res) => {
      row.orderDetailList = res.data.list
    })
    apiMerchants.itemByCode(row.customer_code).then((res) => {
      row.merchantsInfo = res.data
    })
    resolve()
  })
}
function printDataEvent() {
  const $table = tableRef.value
  $table?.openPrint()
}
function exportDataEvent() {
  const $table = tableRef.value
  $table?.openExport()
}
/// ///////////////////////////////////翻页
const submitTopEvent: VxeFormEvents.Submit = () => {
  tablePage.currentPage = 1
  tablePage.pageSize = 10
  const req = {
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    billSn: formTop.billSn,
    priorityLevel: formTop.priorityLevel,
    orderCode: formTop.orderCode,
    customerName: formTop.customerName,
    routeName: formTop.routeName,
    status: formTop.status,
    tempType: formTop.tempType,
  }
  apiPage(req)
}

const resetTopEvent: VxeFormEvents.Reset = () => {
  tablePage.currentPage = 1
  tablePage.pageSize = 10
  const req = {
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    billSn: formTop.billSn,
    priorityLevel: formTop.priorityLevel,
    orderCode: formTop.orderCode,
    customerName: formTop.customerName,
    routeName: formTop.routeName,
    status: formTop.status,
    tempType: formTop.tempType,
  }
  // console.log(req)
  apiPage(req)
}
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
  tablePage.currentPage = currentPage
  tablePage.pageSize = pageSize
  const req = {
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    billSn: formTop.billSn,
    priorityLevel: formTop.priorityLevel,
    orderCode: formTop.orderCode,
    customerName: formTop.customerName,
    routeName: formTop.routeName,
    status: formTop.status,
    tempType: formTop.tempType,
  }
  apiPage(req)
}
/// ///////////////////////////////////生命周期
onBeforeMount(() => {
  g.getDicts('delivery_priority').then((res: any) => {
    pageData.priorityLevelList = res.data.list
  })
  g.getDicts('storage_type').then((res: any) => {
    pageData.storageTypeList = res.data.list
  })
  g.getDicts('order_delivery_state').then((res: any) => {
    pageData.orderDeliveryStateList = res.data.list
  })
})
onMounted(() => {
  tablePage.currentPage = 1
  tablePage.pageSize = 10
  const req = {
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    billSn: formTop.billSn,
    priorityLevel: formTop.priorityLevel,
    orderCode: formTop.orderCode,
    customerName: formTop.customerName,
    routeName: formTop.routeName,
    status: formTop.status,
    tempType: formTop.tempType,
  }
  apiPage(req)
  apiListRoute()
})
</script>

<template>
  <div class="page-wrap">
    <div class="page-top">
      <vxe-form :data="formTop" style="padding-left: 5px;" @submit="submitTopEvent" @reset="resetTopEvent">
        <vxe-form-item title="订单编号" field="orderCode" :item-render="{}">
          <template #default="{ data }">
            <vxe-input v-model="data.orderCode" placeholder="请输入订单编号" clearable />
          </template>
        </vxe-form-item>
        <vxe-form-item title="客户名称" field="customerName" :item-render="{}">
          <template #default="{ data }">
            <vxe-input v-model="data.customerName" placeholder="请输入客户名称" clearable />
          </template>
        </vxe-form-item>
        <vxe-form-item title="线路" field="routeName" :item-render="{}">
          <template #default="{ data }">
            <vxe-select v-model="data.routeName" placeholder="请选择线路" clearable>
              <vxe-option v-for="(item, index) in pageData.routeList" :key="index" :value="item.name" :label="item.name" />
            </vxe-select>
          </template>
        </vxe-form-item>
        <vxe-form-item title="温控要求" field="tempType" :item-render="{}">
          <template #default="{ data }">
            <vxe-select v-model="data.tempType" placeholder="请选择温控要求" clearable>
              <vxe-option v-for="(item, index) in pageData.storageTypeList" :key="index" :value="item.value" :label="item.label" />
            </vxe-select>
          </template>
        </vxe-form-item>
        <vxe-form-item title="优先级" field="priorityLevel" :item-render="{}">
          <template #default="{ data }">
            <vxe-select v-model="data.priorityLevel" placeholder="请选择优先级" clearable>
              <vxe-option v-for="(item, index) in pageData.priorityLevelList" :key="index" :value="item.value" :label="item.label" />
            </vxe-select>
          </template>
        </vxe-form-item>
        <vxe-form-item title="运单号" field="billSn" :item-render="{}">
          <template #default="{ data }">
            <vxe-input v-model="data.billSn" placeholder="请输入运单号" clearable />
          </template>
        </vxe-form-item>
        <vxe-form-item title="派送状态" field="status" :item-render="{}">
          <template #default="{ data }">
            <vxe-select v-model="data.status" placeholder="请选择派送状态" clearable>
              <vxe-option v-for="(item, index) in pageData.orderDeliveryStateList" :key="index" :value="item.value" :label="item.label" />
            </vxe-select>
          </template>
        </vxe-form-item>
        <vxe-form-item>
          <template #default>
            <vxe-button type="submit" status="primary" content="搜索" />
            <vxe-button type="reset" content="重置" />
          </template>
        </vxe-form-item>
      </vxe-form>
      <vxe-toolbar>
        <template #buttons>
          <vxe-button style="margin-left: 5px;" @click="newOrg">
            新增
          </vxe-button>
          <vxe-button @click="removeSelected">
            删除选中
          </vxe-button>
          <vxe-button @click="manualSync">
            手动同步
          </vxe-button>
          <vxe-button status="primary" style="margin-left: 5px;" icon="vxe-icon-file-excel" @click="exportDataEvent">
            导出
          </vxe-button>
          <!-- <vxe-button style="margin-left: 5px;" icon="vxe-icon-print" @click="printSelectEvent">
            打印选中
          </vxe-button> -->
          <vxe-button status="primary" style="margin-left: 5px;" icon="vxe-icon-print" @click="printDataEvent">
            打印
          </vxe-button>
        </template>
      </vxe-toolbar>
    </div>
    <page-main>
      <vxe-table
        ref="tableRef" auto-resize border stripe :loading="pageData.loading" :column-config="{ resizable: true }"
        :row-config="{ isHover: true }" :checkbox-config="{ highlight: true, range: true }" :data="pageData.tableData"
        align="center" header-align="center"
        :export-config="{}"
        :print-config="pageData.tablePrint"
        :expand-config="{ lazy: true, loadMethod: loadContentMethod, iconOpen: 'vxe-icon-square-minus', iconClose: 'vxe-icon-square-plus' }"
      >
        <vxe-column type="checkbox" width="50" />
        <vxe-column field="order_code" align="center" title="订单编号" />
        <vxe-column title="订单详情" type="expand" width="100">
          <template #default>
            <span>点击查看</span>
          </template>
          <template #content="{ row }">
            <div style="padding-left: 10px;padding-right: 10px;padding-bottom: 20px;">
              <div v-if="row.trans_temp_type === 'LC'">
                <div style="display: flex;justify-content: center;padding-top: 10px;padding-bottom: 10px;">
                  <a-text style="color: red;">
                    冷藏运输温度
                  </a-text>
                </div>
                <div style="display: flex;justify-content: center;align-items: center;">
                  <vxe-input v-model="row.start_temp" type="float" placeholder="起运温度" clearable />
                  <div>℃----</div>
                  <vxe-input v-model="row.end_temp" type="float" placeholder="送达温度" clearable />℃
                  <vxe-button @click="sumbitTemp(row)">
                    提交
                  </vxe-button>
                </div>
              </div>
              <div style="display: flex;justify-content: center;padding-top: 10px;padding-bottom: 10px;">
                <a-text style="color: red;">
                  客商信息
                </a-text>
              </div>
              <div style="border: 1px solid #f56a00;border-radius: 25px;padding: 10px;">
                <vxe-form :data="row.merchantsInfo" title-width="80">
                  <vxe-form-gather span="24">
                    <vxe-form-item title="名称" field="name" :item-render="{}" span="12" />
                    <vxe-form-item title="编号" field="short_name" :item-render="{}" span="12" />
                  </vxe-form-gather>
                  <vxe-form-gather span="24">
                    <vxe-form-item title="省" field="province" :item-render="{}" span="4" />
                    <vxe-form-item title="市" field="city" :item-render="{}" span="4" />
                    <vxe-form-item title="区" field="county" :item-render="{}" span="4" />
                    <vxe-form-item title="详细地址" field="addr" :item-render="{}" span="12" />
                  </vxe-form-gather>
                  <vxe-form-gather span="24">
                    <vxe-form-item title="经度" field="lat" :item-render="{}" span="12" />
                    <vxe-form-item title="维度" field="lng" :item-render="{}" span="12" />
                  </vxe-form-gather>
                  <vxe-form-gather span="24">
                    <vxe-form-item title="联系人" field="contact" :item-render="{}" span="12" />
                    <vxe-form-item title="联系方式" field="telephone" :item-render="{}" span="12" />
                  </vxe-form-gather>
                  <vxe-form-gather span="24">
                    <vxe-form-item title="线路" field="route_name" :item-render="{}" span="12" />
                  </vxe-form-gather>
                </vxe-form>
              </div>
              <div style="display: flex;justify-content: center;padding-top: 10px;padding-bottom: 10px;">
                <a-text style="color: red;">
                  订单明细
                </a-text>
              </div>
              <vxe-table style="border: 1px solid #f56a00;" :data="row.orderDetailList" align="center" header-align="center">
                <vxe-column field="order_code" title="订单号" />
                <vxe-column field="order_line_num" title="行号" />
                <vxe-column field="product_name" title="商品名称" />
                <vxe-column field="specifications" title="规格/型号" />
                <vxe-column field="manufacturer" title="生产厂家" />
                <vxe-column field="approval_num" title="国药准字号" />
                <vxe-column field="permit_holder" title="上市许可持有人" />
                <!-- <vxe-column field="formula" title="剂型" /> -->
                <vxe-column field="storage_type" title="温控要求" :formatter="formatterStorageType" />
                <vxe-column field="lot_num" title="批号" />
                <vxe-column field="product_date" title="生产日期" />
                <vxe-column field="expire_date" title="有效期至" />
                <vxe-column field="approval_valid_time" title="批件效期" />
                <vxe-column field="count" title="数量" />
                <vxe-column field="unit" title="单位" />
              </vxe-table>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="customer_name" align="center" title="客户名称" />
        <vxe-column field="route" align="center" title="线路" />
        <vxe-column field="pack_count" align="center" title="箱/包数" />
        <vxe-column field="trans_temp_type" title="温控要求">
          <template #default="{ row }">
            <div v-if="row.trans_temp_type === 'LC'" style="display: flex;flex-direction: column;">
              <el-text>{{ funcStorageType(row.trans_temp_type) }}</el-text>
              <div style="display: flex;flex-direction: column;justify-content: flex-start;align-items: flex-start;width: 100%;">
                <el-text>起运温度:{{ row.start_temp || '----' }}℃</el-text>
                <el-text>送达温度:{{ row.end_temp || '----' }}℃</el-text>
              </div>
            </div>
            <div v-else>
              <el-text>{{ funcStorageType(row.trans_temp_type) }}</el-text>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="priority_level" align="center" title="优先级" :formatter="formatterPriorityLevel" />
        <vxe-column field="trans_bill_sn" align="center" title="运单号">
          <template #default="{ row }">
            {{ row.trans_bill_sn || '待分配' }}
          </template>
        </vxe-column>
        <vxe-column field="status" align="center" title="派送状态" :formatter="formatterDeliveryStatus" />
        <vxe-column title="操作" fixed="right" width="200">
          <template #default="{ row }">
            <!-- <vxe-button type="text" @click="editItem(row)">
              编辑
            </vxe-button> -->
            <vxe-button type="text" @click="delItem(row)">
              删除
            </vxe-button>
          </template>
        </vxe-column>
      </vxe-table>
    </page-main>
    <div class="page-opration-container">
      <vxe-pager
        v-model:current-page="tablePage.currentPage" v-model:page-size="tablePage.pageSize"
        :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
        :total="tablePage.total" @page-change="handlePageChange"
      />
    </div>
    <div>
      <vxe-modal v-model="pageData.modalShow" width="800">
        <template #title>
          <span style="color: red;">{{ pageData.modalName }}</span>
        </template>
        <template #default>
          <vxe-form ref="refModalForm" :data="modalFormData" :rules="formRules" title-width="100">
            <vxe-form-item title="名称" field="name" :item-render="{}">
              <template #default="{ data }">
                <vxe-input v-model="data.name" placeholder="请输入名称" clearable />
              </template>
            </vxe-form-item>
            <vxe-form-item title="负责人" field="principal" :item-render="{}">
              <template #default="{ data }">
                <vxe-input v-model="data.principal" placeholder="请输入负责人" clearable />
              </template>
            </vxe-form-item>
            <vxe-form-item title="地址" field="addr" :item-render="{}">
              <template #default="{ data }">
                <vxe-input v-model="data.addr" placeholder="请输入地址" clearable />
              </template>
            </vxe-form-item>
            <vxe-form-item title="电话" field="phone" :item-render="{}">
              <template #default="{ data }">
                <vxe-input v-model="data.phone" placeholder="请输入电话" clearable />
              </template>
            </vxe-form-item>
          </vxe-form>
          <div style="display: flex;justify-content: flex-end;">
            <vxe-button content="取消" @click="cancelModalEvent" />
            <vxe-button status="primary" content="提交" @click="sumbitModalEvent" />
          </div>
        </template>
      </vxe-modal>
    </div>
  </div>
</template>

  <style lang="scss" scoped>
  .page-wrap {
    position: absolute;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .page-top {
      margin-top: 5px;
      padding-left: 20px;
      padding-right: 20px;
    }

    .page-main {
      flex: 1;
      overflow: auto;
      margin-bottom: 5px;
      margin-top: 5px;
      padding-top: 5px;
    }

    .page-opration-container {
      display: flex;
      justify-content: center;
      align-items: center;
      padding-bottom: 5px;
    }
  }
  </style>
